package org.ghost.wechat.platform.util;

import org.apache.commons.lang3.ArrayUtils;
import org.ghost.wechat.platform.common.enumeration.IErrorCodeEnum;
import org.ghost.wechat.platform.common.exception.AppRuntimeException;
import org.slf4j.Logger;

/**
 * 异常工具
 *
 * @author 01
 */
final public class ExceptionUtil {
    public static void throwRuntimeException(String method, String message, Logger logger) throws RuntimeException {
        if (logger != null && logger.isWarnEnabled()) {
            logger.warn("{} 业务异常: {}", method, message);
        }

        throw new RuntimeException(method + message);
    }

    public static void throwRuntimeException(IErrorCodeEnum errorCode, String method, Logger logger) throws RuntimeException {
        if (logger != null && logger.isWarnEnabled()) {
            logger.warn("{} 业务异常: {}", method, errorCode != null ? errorCode.getMessage() : "null");
        }

        throw new AppRuntimeException(errorCode);
    }

    public static String getExceptionStack(Throwable e) {
        StringBuilder builder = new StringBuilder(e.toString() + e.getMessage() + "\n");
        StackTraceElement[] stackTraceElements = e.getStackTrace();
        if (ArrayUtils.isNotEmpty(stackTraceElements)) {
            for (int index = stackTraceElements.length - 1; index >= 0; --index) {
                builder.append("at [").append(stackTraceElements[index].getClassName()).append(",");
                builder.append(stackTraceElements[index].getFileName()).append(",");
                builder.append(stackTraceElements[index].getMethodName()).append(",");
                builder.append(stackTraceElements[index].getLineNumber()).append("]\n");
            }
        }
        return builder.toString();
    }
}
